package com.sl.au.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Division;
import com.sl.au.entity.GridAreaInfo;
import com.sl.au.entity.Hierarchy;
import com.sl.au.entity.User;
import com.sl.au.service.DivisionService;
import com.sl.au.service.GridAreaInfoService;
import com.sl.au.service.HierarchyService;
import com.sl.au.service.UserService;
import com.sl.utils.MsgHelper;

/**
 * 用户与单元表格的绑定
 * 
 * @author HeGuangChuan
 *
 */
@RestController
@RequestMapping("/ui/userGrid")
public class UserGridController extends BaseController {

	@Autowired
	private UserService userService;
	@Autowired
	private GridAreaInfoService gridAreaInfoService;
	@Autowired
	private DivisionService divisionService;
	@Autowired
	private HierarchyService hierarchyService;

	/**
	 * 未绑定组织的用户信息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/showUserUnbindHierarchyPage", method = RequestMethod.POST)
	public Map<String, Object> showUserUnbindHierarchyPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");// 区域id
		String con = request.getParameter("con");
		List<User> users = null;
		int count = 0;
		if ("0".equals(key)) {
			if (StringUtils.hasText(con)) {
				users = userService.findUsersUnbindHierarchyOnlyCon(con, start, length);
				count = userService.findUsersUnbindHierarchyCountOnlyCon(con, start, length);
			} else {
				users = userService.findUsersUnbindHierarchyNone(start, length);
				count = userService.findUsersUnbindHierarchyCountNone();
			}

		} else {
			if (StringUtils.hasText(con)) {
				users = userService.findUsersUnbindHierarchyByKeyAndCon(key, con, start, length);
				count = userService.findUsersUnbindHierarchyCountByKeyAndCon(key, con);
			} else {
				users = userService.findUserUnbindHierarchyOnlyKey(key, start, length);
				count = userService.findUserUnbindHierarchyCountOnlyKey(key);
			}
		}

		map.put("data", users);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * 未绑定组织的用户信息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/showUserBindHierarchyPage", method = RequestMethod.GET)
	public Map<String, Object> showUserBindHierarchyPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");// 带过来的key就是组织的id
		String con = request.getParameter("con");
		List<User> users = null;
		int count = 0;
		if ("0".equals(key)) {
			if (StringUtils.hasText(con)) {
				users = userService.findBindByConOnly(con, start, length);
				count = userService.findBindCountByConOnly(con);
			} else {
				users = userService.getBindHierarchyUsersPageNone(start, length, key, "createTime", null);
				count = userService.getBindHierarchyUsersCountNone("");
			}
		} else {
			if (StringUtils.hasText(con)) {
				users = userService.getBindHierarchyUsersPageBykeyAndCon(start, length, key, con);
				count = userService.getBindHierarchyUsersCountByCon(key, con);
			} else {
				users = userService.getBindHierarchyUsersPageBykey(start, length, key, "createTime", null);
				count = userService.getBindHierarchyUsersCount(key);
			}
		}

		map.put("data", users);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * 获取没有绑定区域信息的网格信息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/showGridUnbindDivisonPage", method = RequestMethod.POST)
	public Map<String, Object> showGridUnbindDivisonPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");// 区域id
		String con = request.getParameter("con");// 查询条件
		List<GridAreaInfo> areaInfos = null;
		Integer count = null;
		if ("0".equals(key)) {// 查询所有区域
			if (StringUtils.hasText(con)) {
				areaInfos = gridAreaInfoService.findUnbindDOnlyCon(con, start, length);
				count = gridAreaInfoService.findUnbindDCountOnlyCon(con);
			} else {
				areaInfos = gridAreaInfoService.findUnbindDNone(start, length);
				count = gridAreaInfoService.findUnbindDCountNone();
			}
		} else {// 查询指定区域
			if (StringUtils.hasText(con)) {
				areaInfos = gridAreaInfoService.findUnbindDByKeyAndCon(key, con, start, length);
				count = gridAreaInfoService.findUnbindDCountByKeyAndCon(key, con);
			} else {
				areaInfos = gridAreaInfoService.findUnbindOnlyKey(key, start, length);
				count = gridAreaInfoService.findUnbindCountOnlyKey(key);
			}
		}
		// List<GridAreaInfo> bindDivisionGridsNoPage=new ArrayList<>();

		map.put("data", areaInfos);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * 初始化绑定了区域信息的网格信息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/showGridBindDivisonPage", method = RequestMethod.POST)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");// divisionId
		String con = request.getParameter("con");
		List<GridAreaInfo> areaInfos = null;
		Integer count = null;

		if ("0".equals(key)) {// 查询所有区域下的网格
			if (StringUtils.hasText(con)) {
				areaInfos = gridAreaInfoService.findBindDivisionPageOnlyCon(con, start, length);
				count = gridAreaInfoService.findBindDivisionCountOnlyCon(key, con, start, length);
			} else {
				areaInfos = gridAreaInfoService.findBindDivisionPageNone(start, length);
				count = gridAreaInfoService.findBindDivisionCountNone(start, length);
			}
		} else {// 查询指定区域下的网格
			if (StringUtils.hasText(con)) {
				areaInfos = gridAreaInfoService.findBindDivisionPageByKeyAndCon(key, con, start, length);
				count = gridAreaInfoService.findBindDivisionCountByKeyAndCon(key, con, start, length);
			} else {
				areaInfos = gridAreaInfoService.findBindDivisionPageOnlyKey(key, con, start, length);
				count = gridAreaInfoService.findBindDivisionCountOnlyKey(key, con, start, length);
			}
		}

		map.put("data", areaInfos);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	@RequestMapping(value = "/initHierarchyTree", method = RequestMethod.GET)
	public Map<String, Object> initHierarchyTree() {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Hierarchy> node = null;

		node = hierarchyService.getAllNodes();
		List<Map<String, Object>> nodeMap = new ArrayList<Map<String, Object>>();

		nodeMap = hierarchyService.getNodeMap(node);

		map.put("code", 1);
		map.put("nodes", nodeMap);

		return map;
	}

	@RequestMapping(value = "/initDivisionTree", method = RequestMethod.GET)
	public Map<String, Object> initDivisionTree(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Division> node = null;
		node = divisionService.getAllNodes();
		List<Map<String, Object>> nodeMap = new ArrayList<Map<String, Object>>();

		nodeMap = divisionService.getNodeMap(node);

		map.put("code", 1);
		map.put("nodes", nodeMap);

		return map;
	}

	@RequestMapping("/unbind/{userIds}/{gridIds}")
	public MsgHelper unbind(@PathVariable("userIds") String userIds, @PathVariable("gridIds") String gridIds) {
		// 去掉最后一个逗号
		int j = 0;
		MsgHelper helper = MsgHelper.success();
		gridIds = gridIds.substring(0, gridIds.length() - 1);
		userIds = userIds.substring(0, userIds.length() - 1);
		String[] gridIdArr = gridIds.split(",");
		String[] userIdArr = userIds.split(",");
		int by = gridIdArr.length * userIdArr.length;
		for (String userId : userIdArr) {
			User user = userService.getRepository().findOne(userId);
			for (String gridId : gridIdArr) {
				GridAreaInfo info = gridAreaInfoService.getRepository().findOne(gridId);
				Set<User> users = info.getUsers();
				// 只解除绑定了的信息
				if (!hashBinded(users, user)) {
					continue;
				} else {
					users.remove(user);
					info.setUsers(users);
					gridAreaInfoService.getRepository().save(info);
					++j;
				}

			}
		}

		helper.put("msg", "成功解绑 " + j + " 条记录,已过滤 " + (by - j) + " 条未绑定记录");

		return helper;
	}

	@RequestMapping("/bind/{userIds}/{gridIds}")
	public MsgHelper bind(@PathVariable("userIds") String userIds, @PathVariable("gridIds") String gridIds) {
		// 去掉最后一个逗号
		gridIds = gridIds.substring(0, gridIds.length() - 1);
		userIds = userIds.substring(0, userIds.length() - 1);
		String[] gridIdArr = gridIds.split(",");
		String[] userIdArr = userIds.split(",");
		int i = 0;
		int by = gridIdArr.length * userIdArr.length;
		MsgHelper helper = MsgHelper.success();
		for (String userId : userIdArr) {
			User user = userService.getRepository().findOne(userId);
			for (String gridId : gridIdArr) {
				GridAreaInfo info = gridAreaInfoService.getRepository().findOne(gridId);
				Set<User> users = info.getUsers();
				// 如果之前已经被绑定,不需要再绑定
				if (hashBinded(users, user)) {
					continue;
				} else {
					users.add(user);
					info.setUsers(users);
					gridAreaInfoService.getRepository().save(info);
					++i;
				}

			}
		}

		helper.put("msg", "成功绑定 " + i + " 条记录,过滤掉 " + (by - i) + " 条已绑定信息");

		return helper;
	}

	private boolean hashBinded(Set<User> users, User user) {
		if (users.contains(user)) {
			return true;
		}
		return false;
	}

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index(ModelAndView modelAndView) {
		modelAndView = createLayoutView("userGrid/index");
		List<User> users = userService.getRepository().findAll();
		modelAndView.addObject("users", users);
		modelAndView.addObject("userSize", users.size());
		List<GridAreaInfo> grids = gridAreaInfoService.getRepository().findAll();
		modelAndView.addObject("grids", grids);
		modelAndView.addObject("gridSize", grids.size());
		return modelAndView;
	}
}
